import fs from 'fs';
import path from 'path';
import archiver from 'archiver';

const __dirname = process.cwd();
var zipDist = path.join(__dirname, '../src-tauri/target/forguncyJavaExtensionGenerateTool.zip');
const destinationFilePath = path.join(__dirname, '../src-tauri/target/forguncyJavaExtensionGenerateTool_1.0.0_x64_zh-CN.msi')

if (fs.existsSync(destinationFilePath)) {
    fs.unlink(destinationFilePath, (err) => {
        if (err) {
            console.error('error when delete:', err);
        } else {
            console.log('delete success');
        }
    });
}

if (fs.existsSync(zipDist)) {
    fs.unlink(zipDist, (err) => {
        if (err) {
            console.error('error when delete:', err);
        } else {
            console.log('delete success');
        }
    });
}
const output = fs.createWriteStream(zipDist);

const archive = archiver('zip');

// 监听输出流的 'close' 事件，表示 ZIP 包创建完成
output.on('close', () => {
    console.log('ZIP create success at:');
    console.log(path.join(__dirname, '../src-tauri/target'));
});

// 监听输出流的 'error' 事件，处理任何错误
output.on('error', (err) => {
    console.error('error when create ZIP:', err);
});

// 使用 archiver 将文件夹添加到 ZIP 包中
var file1 = path.join(__dirname, '../src-tauri/target/release/forguncyJavaExtensionGenerateTool.exe');
const command = path.join(__dirname, '../src-tauri/target/release/command-plugin-template');
const securityProvider = path.join(__dirname, '../src-tauri/target/release/security-provider-template');
const webApi = path.join(__dirname, '../src-tauri/target/release/web-api-template');
const packageTools = path.join(__dirname, '../src-tauri/target/release/packageTools');

archive.pipe(output);
archive
    .append(fs.createReadStream(file1), { name: "forguncyJavaExtensionGenerateTool.exe" })
    .directory(command, "command-plugin-template")
    .directory(securityProvider, "security-provider-template")
    .directory(webApi, "web-api-template")
    .directory(packageTools, "packageTools")
archive.finalize();




const sourceFilePath = '../src-tauri/target/release/bundle/msi/forguncyJavaExtensionGenerateTool_1.0.0_x64_zh-CN.msi';

fs.copyFile(sourceFilePath, destinationFilePath, (err) => {
    if (err) {
        console.error('error when copy:', err);
    } else {
        console.log('copy success');
    }
});